package com.alisls.demo.springcloud.gateway.filter;

import com.alisls.demo.springcloud.common.model.dto.DefaultResult;
import com.alisls.demo.springcloud.common.model.dto.Result;
import com.alisls.demo.springcloud.gateway.config.GatewayProp;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * OAuth过滤器
 *
 * @author Ke Wang
 * @date 2020/10/30
 */
@Component
@Log4j2
public class OAuthFilter implements GlobalFilter, Ordered {

    @Resource
    private GatewayProp gatewayProp;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求头
        HttpHeaders headers = request.getHeaders();

        // 要忽略的Url
        List<String> ignoreUrls = gatewayProp.getIgnoreUrls();

        // 打印配置要忽略的Url信息
        printIgnoreUrls(ignoreUrls);

        // 请求路径
        String path = request.getURI().getPath();
        // 判断如果是要忽略的url则不进行处理
        if (ignoreUrls != null) {
            for (String ignoreUrl: ignoreUrls) {
                if (!path.equals(ignoreUrl)) {
                    continue;
                }

                return chain.filter(exchange);
            }
        }

        // 判断有没有传Token
        List<String> authorizations = headers.get("Authorization");
        if (CollectionUtils.isEmpty(authorizations)) {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);

            String message = "Token不能为空！";
            Result result = DefaultResult.ofFail(message);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                message = objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            DataBuffer buffer = response.bufferFactory().wrap(message.getBytes());
            return response.writeWith(Mono.just(buffer));
        }

        String token = authorizations.get(0);
        log.info("获取Token值：{}", token);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

    private void printIgnoreUrls(List<String> ignoreUrls) {
        if (ignoreUrls == null || ignoreUrls.size() <= 0) {
            log.info("未配置要忽略的urls");
            return;
        }

        for (String ignoreUrl: ignoreUrls) {
            log.info("要忽略的urls：{}", ignoreUrls);
        }
    }

}
